<template>
	<view class="content">
		<!-- 创建账单页面 -->
		<view class="content-category">
			<uv-grid :col="4" :border="false" >
				<uv-grid-item v-for="(item, index) in category" :key="index">
					<view class="content-group-user-item" :class="{ 'active': item.select }"  @click="selectCategory(item.id,index)">
						<uv-avatar customStyle="margin:0 auto"  :src="item.icon" shape="square"></uv-avatar>
						<text class="grid-text">{{ item.title }}</text>
					</view>
				</uv-grid-item>
			</uv-grid>
		</view>
		<uv-line></uv-line>
		<view class="content-money" @click="openTotalMoney()">
			<uv-keyboard ref="keyboard" mode="number" :tips="total_money" @change="changeTotalMoney" @backspace="backspace" @confirm="inputTotalMoney"></uv-keyboard>
			<span>总金额:{{ total_money }}</span>
		</view>
		<uv-line></uv-line>
		<view class="content-group">
			<uv-popup ref="popup" mode="center" round="8">
				<view class="content-group-user">
					<uv-grid  :border="false" >
						<uv-grid-item v-for="(item, index) in chengyuan" :key="index">
							<view class="content-group-user-item" :class="{ 'active': item.select }"  @click="selectUser(item.user_id,index)">
								<uv-avatar customStyle="margin:0 auto" :src="`${apiConfig.baseUrl}`+item.avatar" shape="square"></uv-avatar>
								<text class="grid-text">{{ item.title }}</text>
							</view>
						</uv-grid-item>
					</uv-grid>
					<view style="width: 200rpx;margin: 20rpx auto;">
						<uv-button type="primary" size="small" text="确定" @click="popupUserClose()" ></uv-button>
					</view>
				</view>
			</uv-popup>
			<uv-cell-group>
				<uv-cell icon="calendar" :isLink="true" arrow-direction="right" @click="popupUser">
					<template v-slot:title>
						<text>选择成员</text>
					</template>
				</uv-cell>
				<uv-cell icon="account"  v-for="(item,index) in selectedMembers" :key="index">
					<template v-slot:title>
						<view  style="display: flex; align-items: center;">
							<text>{{ item.title }}</text>&nbsp;&nbsp;
							<uv-input placeholder="" border="bottom" type="digit" v-model="item.gr_money" ></uv-input>
						</view>
					</template>
				</uv-cell>
			</uv-cell-group>

		</view>
		<uv-line></uv-line>



		<view class="content-bill">
			<uv-calendars ref="calendars" @confirm="selectDate" />
			<uv-datetime-picker ref="datetimePicker" v-model="shijian" mode="time"  @confirm="selectTime">
		</uv-datetime-picker>
			<uv-cell-group>
				<uv-cell icon="calendar" :isLink="true" arrow-direction="right" @click="datePick">
					<template v-slot:title>
						<text>日期</text>&nbsp;&nbsp;
						<text>{{ riqi }}</text>
					</template>
				</uv-cell>
				<uv-cell icon="clock" :isLink="true" arrow-direction="right" @click="timePick">
					<template v-slot:title>
						<text>时间</text>&nbsp;&nbsp;
						<text>{{ shijian }}</text>
					</template>
				</uv-cell>
				<uv-cell icon="order"  >
					<template v-slot:title>
						<view  style="display: flex; align-items: center;">
							<text>备注</text>&nbsp;&nbsp;
							<uv-input placeholder="备注" border="bottom" v-model="remark" ></uv-input>
						</view>
					</template>
				</uv-cell>
			</uv-cell-group>
		</view>
	</view>
	<view style="width: 200rpx;margin: 20rpx auto;">
		<uv-button type="primary" :disabled="isSubmit" text="提交" @click="submit()" ></uv-button>
	</view>
</template>

<script setup>
import { ref,computed,onMounted } from 'vue';
import { useStore } from 'vuex';
import { apiConfig } from '../../apiConfig.js';
const store = useStore().state;
onMounted(() => {
	console.log("页面加载")
	showDateTime();
	// console.log(chengyuan.value.filter(member => member.select))
});
const category = ref([
	{ "id": 1, "title": "蔬菜", "icon": "/static/icon_category/a-083_shucai.png" ,"select":true },
	{ "id": 2, "title": "房租", "icon": "/static/icon_category/a-083_jiudian.png" },
	{ "id": 3, "title": "水电", "icon": "/static/icon_category/shuidian.png"},
	{ "id": 4, "title": "水果", "icon": "/static/icon_category/a-083_guoqie.png" },
	{ "id": 5, "title": "打车", "icon": "/static/icon_category/a-083_dache.png" },
	{ "id": 6, "title": "超市", "icon": "/static/icon_category/a-083_chaoshi.png" },
]);
const category_id=ref(1);
function selectCategory(id,index) {
	category.value.forEach(item => {
		item.select = false;
	});
	category.value[index].select=true;
	category_id.value=id;
}

const chengyuan = ref([
	{ "user_id": 1, "title": "李策", "avatar": "/upload/avatar/2023-09-11/qqxhh4.jpeg","select":true,"gr_money":0.00 },
	{ "user_id": 2, "title": "薛海洋", "avatar": "/upload/avatar/2023-09-21/xue.jpg","select":true,"gr_money":0.00 },
	{ "user_id": 3, "title": "常磊财", "avatar": "/upload/avatar/2023-09-21/chang.jpg","select":true,"gr_money":0.00 },
]);

const total_money = ref("0");//总金额
const keyboard = ref(null);
const openTotalMoney = () => {
	  if (keyboard.value) {
		keyboard.value.open();
	  }
	};
const changeTotalMoney = (val) =>{
	// console.log(val);
	if(total_money.value==="0.00"){total_money.value=""}
	total_money.value += String(val)
	// console.log(total_money.value)
}
const backspace = () =>{
	// 删除value的最后一个字符
	if (total_money.value.length) total_money.value = total_money.value.substr(0, total_money.value.length - 1);
	// console.log(total_money.value);
}
//输入总金额点确认触发
const inputTotalMoney = () =>{
	//根据
	divideEqually(chengyuan, total_money.value);
}
// 平分金额时保留两位小数，并且在除不尽的情况下对其中一个成员进行补齐
const divideEqually = (chengyuan, amount) => {
  // 计算 select 为 true 的成员数量
  const selectedMembers = chengyuan.value.filter(member => member.select);
  const totalSelected = selectedMembers.length;
  
  // 如果没有任何成员被选中，或者金额为 0，则不进行操作
  if (totalSelected === 0 || amount === 0) {
    return;
  }

  // 计算平分金额，并保留两位小数
  const shareAmount = (amount / totalSelected).toFixed(2);

  // 更新每个选中成员的 gr_money
  selectedMembers.forEach((member, index) => {
    // 补齐金额，使得总金额等于初始金额
    const finalAmount = parseFloat(shareAmount) + (index === totalSelected - 1 ? (amount - totalSelected * parseFloat(shareAmount)) : 0);
    member.gr_money = finalAmount.toFixed(2);
  });
};

const popup = ref(null);
const popupUser=()=>{
	// console.log(123);
	popup.value.open();
}
//弹窗确认关闭
const popupUserClose=()=>{
	//计算每人应该承担多少钱,自动填充到input框
	popup.value.close();
}

// 创建计算属性
const selectedMembers = computed(() => {
      return chengyuan.value.filter(member => member.select);
});

// const selectUser = (id,index) =>{
	
// 	console.log(chengyuan.value)
// }
function selectUser(id,index) {
	chengyuan.value[index].select=!chengyuan.value[index].select;
	// console.log(chengyuan.value)
}


const riqi = ref("");
const shijian = ref("");
const calendars = ref(null);
const datePick = () => {
	  if (calendars.value) {
		calendars.value.open();
	  }
	};
const selectDate = (e) => {
	// console.log(e);
	riqi.value = e.fulldate
};
const selectTime = (e) => {
	// console.log(e);
	shijian.value = e.value
};

const datetimePicker = ref(null);
const timePick =()=>{
	if (datetimePicker.value) {
        datetimePicker.value.open();
      }
}
function showDateTime() {
	var date = new Date(); // 获取当前日期和时间
	var year = date.getFullYear(); // 年份
	var month = date.getMonth() + 1; // 月份（0-11）
	var day = date.getDate(); // 日
	var hours = date.getHours(); // 小时
	var minutes = date.getMinutes(); // 分钟
	var seconds = date.getSeconds(); // 秒
	// 格式化月份、小时、分钟和秒，确保它们是两位数
	month = month < 10 ? '0' + month : month;
	hours = hours < 10 ? '0' + hours : hours;
	minutes = minutes < 10 ? '0' + minutes : minutes;
	seconds = seconds < 10 ? '0' + seconds : seconds;
	// 构建日期时间字符串
	var dateTimeString = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
	riqi.value = year + '-' + month + '-' + day;
	shijian.value = hours + ':' + minutes 
}

const remark = ref("");


// 计算select为true的gr_money总和
function calculateSelectedGrMoney(data) {
  return data.reduce((total, member) => {
    if (member.select) {
		let grMoney = parseFloat(member.gr_money);
		// 如果转换成功且不是NaN，则加到总和中
		if (!isNaN(grMoney)) {
			return total + grMoney;
		}
    }
    return total;
  }, 0);
}
const isSubmit = ref(false);
//提交
function submit(){
	isSubmit.value = true;
	// 验证总金额和子金额是否相等
	let grmoney=calculateSelectedGrMoney(chengyuan.value);
	// console.log(selectedMembers.value);
	let numStr = total_money.value;
	let num = parseFloat(numStr);
	// console.log(riqi.value+" "+shijian.value+":00");
	// return ;
	console.log(grmoney);
	console.log(num);
	if(grmoney!=num){
		uni.showToast({
			title: '提交失败,检查总金额是否和子金额相等',
			icon: 'none'
		});
		return
	}
	// return;
	uni.request({
        url: `${apiConfig.baseUrl}`+'/add_bill_record',
        method: 'POST',
        data: {
			"user_id":store.loginInfo.id,
			"bill_datetime":riqi.value+" "+shijian.value+":00",
			"money":total_money.value,
			"remark":remark.value,
			"category":category_id.value,
			"gid":1,
			"data":selectedMembers.value
		},
        success: (res) => {
			// console.log(res);
			uni.showToast({
				title: res.data.msg,
				icon: 'none'
			});
			return;
        },
        fail: (err) => {
          console.error('提交失败：', err);
        }
    });
}
</script>

<style>
.content {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	/* background-color: rgb(216, 216, 215); */
}

.content-category {
	width: 98vw;
}
.content-bill {
	width: 98vw;
}
.content-money{
	width: 98vw;
	text-align: left;
	/* font-weight: bold; */
  	font-size: larger; /* 文字放大 */
	padding: 10px 15px;
}
.content-group{
	width: 98vw;
}
.content-group-user{
	padding: 40rpx;
	width: 600rpx;
	/* height: 400rpx; */
}
.active {
	
  background-color: #9df2bf;
  /* border: 1px solid #1c743f; */
}
.content-group-user-item{
	width: 100%;
	height: 100%;
	margin: 3rpx;
	margin-left: 10rpx;
	padding-top: 15rpx;
	padding-bottom: 10rpx;
	border-radius: 15px;
	text-align: center;

}
</style>
